//
//  QRCodeViewController.m
//  QRCode
//
//  Created by 王聪 on 16/5/22.
//  Copyright © 2016年 王聪. All rights reserved.
//

#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SQCodeViewController.h"

@interface QRCodeViewController () <UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate>

// 显示扫描后的结果
@property (weak, nonatomic) IBOutlet UILabel *resultLab;



// 扫描线
@property (weak, nonatomic) IBOutlet UIImageView *scanLineView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanLineCons;

@property (weak, nonatomic) IBOutlet UIImageView *scanBack;


// 会话
@property (nonatomic, strong) AVCaptureSession *session;

// 输入设备
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;

// 输出设备
@property (nonatomic, strong) AVCaptureMetadataOutput *output;

// 预览图层
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

// 会话图层
@property (nonatomic, strong) CALayer *drawLayer;


// 扫描完成回调block
@property (copy, nonatomic) void (^completionBlock) (NSString *);

// 音频播放
@property (strong, nonatomic) AVAudioPlayer *beepPlayer;

@property (weak, nonatomic) IBOutlet UIView *scanView;

@property (nonatomic,assign) BOOL isCanScan;

@end

@implementation QRCodeViewController

#pragma mark - 懒加载
// 会话
- (AVCaptureSession *)session
{
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
        [_session setSessionPreset:AVCaptureSessionPresetHigh];
    }
    return _session;
}
// 拿到输入设备
- (AVCaptureDeviceInput *)deviceInput
{
    if (_deviceInput == nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        _deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];
    }
    return _deviceInput;
}
// 拿到输出对象
- (AVCaptureMetadataOutput *)output
{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc] init];
    }
    return _output;
}
// 创建预览图层
- (AVCaptureVideoPreviewLayer *)previewLayer
{
    if (_previewLayer == nil) {
        _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
        _previewLayer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        _previewLayer.videoGravity =AVLayerVideoGravityResizeAspectFill;
    }
    return _previewLayer;
}


- (AVAudioPlayer *)beepPlayer
{
    if (_beepPlayer == nil) {
        NSString * wavPath = [[NSBundle mainBundle] pathForResource:@"beep" ofType:@"wav"];
        NSData* data = [[NSData alloc] initWithContentsOfFile:wavPath];
        _beepPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
    }
    return _beepPlayer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
//    self.navigationItem.title = @"扫一扫";
    self.hidNav = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
     if ([self startScan] && self.isCanScan) {
         [self.session startRunning];
     }
     [self startAnimation];

}


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
 
}



#pragma mark - Managing the Block

- (void)setCompletionWithBlock:(void (^) (NSString *resultAsString))completionBlock
{
    self.completionBlock = completionBlock;
}


#pragma 扫描过程
- (BOOL)startScan{
    // 1.判断是否能够将输入添加到会话中
    if (![self.session canAddInput:self.deviceInput]) {
        return YES;
    }
    
    // 2.判断是否能够将输出添加到会话中
    if (![self.session canAddOutput:self.output]) {
        return YES;
    }
    
    // 3.将输入和输出都添加到会话中
    [self.session addInput:self.deviceInput];
    
    [self.session addOutput:self.output];
    
    // 4.设置输出能够解析的数据类型
    // 注意: 设置能够解析的数据类型, 一定要在输出对象添加到会员之后设置, 否则会报错
    self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 如果想实现只扫描一张图片, 那么系统自带的二维码扫描是不支持的
    // 只能设置让二维码只有出现在某一块区域才去扫描
//    self.output.rectOfInterest = CGRectMake(0.0, 0.0, 1, 1);
    
    // 设置二维码区域参开http://www.tuicool.com/articles/6jUjmur
    CGFloat ScreenHigh = [UIScreen mainScreen].bounds.size.height;
    CGFloat ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    [self.output setRectOfInterest : CGRectMake (( 160 )/ ScreenHigh ,(( ScreenWidth - 300 )/ 2 )/ ScreenWidth , 300 / ScreenHigh , 300 / ScreenWidth)];
    
    // 5.添加预览图层
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];

    
    // 6.告诉session开始扫描
    [self.session startRunning];
    self.isCanScan = YES;
    return NO;
}

- (void)stopScan
{
    if ([self.session isRunning]) {
        [self.session stopRunning];
    }

    [self stopAnimation];
}




- (void)startAnimation
{
    
    [UIView animateWithDuration:2.0 animations:^{
        _scanLineView.transform = CGAffineTransformMakeTranslation(0, _scanBack.frame.size.height - 4);
    } completion:^(BOOL finished) {
        _scanLineView.transform = CGAffineTransformIdentity;
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(startAnimation) object:nil];
        [self performSelector:@selector(startAnimation) withObject:nil afterDelay:0.1];
    }];
    

}

// 停止动画
- (void)stopAnimation{
    [self.view.layer removeAllAnimations];
}

/**
 *  当从二维码中获取到信息时，就会调用下面的方法
 *
 *  @param captureOutput   输出对象
 *  @param metadataObjects 信息
 *  @param connection asda
 */
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
   
    
    if (metadataObjects.count == 0 || metadataObjects == nil) {
        return;
    }
    
    
    // 1.获取扫描到的数据
    // 注意: 要使用stringValue

    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects lastObject];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode] && [metadataObj isKindOfClass:[AVMetadataMachineReadableCodeObject class]]) {
        
            // 扫描结果
            NSString *result = [metadataObjects.lastObject stringValue];
            
            NSLog(@"%@",result);
            
            if ([result containsString:@"http"]) {
            

            } else {
                NSDictionary * dic = [self turnStringToDictionary:result];
                
                SQ_LOG(@"%@",dic[@"ipm_id"]);
                SQCodeViewController * codeVC = SQCodeViewController.new;
                codeVC.ipm_id = dic[@"ipm_id"];
                codeVC.type = @"1";
              
                [self pushVC:codeVC];
                

            }
            
            // 停止扫描
            [self stopScan];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }
    }

    
   
}



-(void)backTouch{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}



-(NSDictionary *)turnStringToDictionary:(NSString *)turnString{
    NSData *turnData = [turnString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *turnDic = [NSJSONSerialization JSONObjectWithData:turnData options:NSJSONReadingMutableLeaves error:nil];
    return turnDic;
}


@end
